package com.enjoy.ch2;

import jdk.internal.org.objectweb.asm.ClassWriter;
import jdk.internal.org.objectweb.asm.Opcodes;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class MetaspaceTest extends ClassLoader {
    public static void main(String[] args) {
        int i = 0;
        try {

            MetaspaceTest metaspaceTest = new MetaspaceTest();
            for (;;) {
                // ClassWriter作用是生成类的二进制字节码
                ClassWriter classWriter = new ClassWriter(0);
                // 版本号，public，类名，包名，父类，接口
                classWriter.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, "Class" + i, null, "java/lang/Object", null);
                // 返回byte[]
                byte[] bytes = classWriter.toByteArray();
                // 执行类的加载
                metaspaceTest.defineClass("Class" + i, bytes, 0, bytes.length);
                i++;
            }
        } finally {
            System.out.println(i);

        }


    }
}


 class MetaspaceOverFlowTest {

    /**
     * 通过CGLIB模拟向元空间写入数据
     */
    public static void main(String[] args) {
        while (true) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            Enhancer enhancer = new Enhancer();

            enhancer.setSuperclass(MetaspaceOverFlowTest.class);
            enhancer.setUseCache(false);
            enhancer.setCallback(new MethodInterceptor() {
                public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
                    return proxy.invokeSuper(obj, args);
                }
            });

            System.out.println("running...");

            enhancer.create();
        }
    }
}